<?php
// +----------------------------------------------------------------------
// | HkCms Tags管理
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace app\content\controller;

use common\controller\AdminBase;
use think\Db;
use \app\content\validate\Tags as TagsV;

class Tags extends AdminBase {

    //tags列表
    public function index() 
    {
        if ( request()->isPOST() ) {

            if (!isset($_POST['listorder'])) {
                $this->error('请选择');
            }

            $listorder = $_POST['listorder'];

            if (is_array($listorder)) {

                foreach ($listorder as $tagid => $v) {

                    model('content/Tags')->where('tagid',$tagid)->update(array('listorder' => (int) $v));
                }

                $this->success('排序更新成功！', url('index'));

            } else {

                $this->error('排序更新失败！', url('index'));
            }
        }

        return $this->basePage('content/Tags', '', array('listorder' => 'DESC', 'tagid' => 'DESC'));
        
    }

    //修改tags
    public function edit() 
    {
        if ( request()->isPOST() ) {

            $model = model('content/Tags');

            $oldTagsName = input('post.oldtagsname', '', 'trim');

            $tag = input('post.tag', '', 'trim');

            $data = input('post.');

            $TagsV = new TagsV;

            $check = $TagsV->check($data);

            if ( !$check ) {

                $this->error($TagsV->getError());
            }

            if ( $oldTagsName != $tag ) {

                $find = $model->where('tag',$tag)->find();

                if ( $find ) {

                    $this->error('该Tags已经存在！');
                }
            }

            unset($data['_tag']);

            unset($data['oldtagsname']);

            $res = $model->allowField(true)->update($data);

            if ( $res ) {
                
                $this->success('修改成功！', url('index'));
            }

            $this->error('修改失败！');
        }

        $data = model('content/Tags')->get(input('tagid'));

        $this->assign('data',$data);

        return $this->fetch();
    }

    //删除tags
    public function delete() 
    {
        $db = model('content/Tags');

        if ( request()->isPOST() ) {

            if (!isset($_POST['tagid'])) {
                $this->error('请选择');
            }

            $tagid = $_POST['tagid'];

            if (is_array($tagid)) {

                foreach ($tagid as $tid) {

                    $info = $db->where(array('tagid' => $tid))->find();
                    if (!empty($info)) {
                        if ($info->delete() !== false) {
                            Db::name('TagsContent')->where(['tag'=>$info['tag']])->delete();
                        }
                    }
                }

                $this->success("删除成功！");

            } else {

                $this->error("参数错误！");
            }

        } else {

            $tagid = input('tagid', 0, 'intval');

            $info = $db->where('tagid',$tagid)->find();

            if (empty($info)) {

                $this->error("该Tags不存在！");
            }

            if ($db->where('tagid',$tagid)->delete() !== false) {

                Db::name('TagsContent')->where('tag',$info['tag'])->delete();

                $this->success('删除成功！');

            } else {
                $this->error('删除失败！');
            }
        }
    }

    //tags数据重建
    public function create() 
    {
        if ( request()->isPOST() || input('modelid') ) {

            $modelid = input('modelid', 0, 'intval');

            $_GET['modelid'] = $modelid;

            $lun = input('lun', 0, 'intval'); //第几轮 0=>1

            $_GET['zlun'] = $zlun= input('zlun','');//总轮数

            $_GET['mo'] = input('mo','');//模型id

            if ($lun > (int) $_GET['zlun'] - 1) {

                $lun = (int) $_GET['zlun'] - 1;
            }

            $lun = $lun < 0 ? 0 : $lun;

            $mlun = 100;

            $firstRow = $mlun * ($lun < 0 ? 0 : $lun);

            $db = Db::name('TagsContent');

            $tagdb = Db::name('Tags');

            if ( 0 !==  (int) input('delete') ) {
                //清空
                $db->execute('TRUNCATE TABLE  `' . config("database.prefix") . 'tags_content`');

                $tagdb->execute('TRUNCATE TABLE  `' . config("database.prefix") . 'tags`');
            }

            // 只删除一次
            unset($_GET['delete']);

            $model = hk_cache('Model');

            if ( 1 == (int) $_GET['mo'] ) {
                
            } else {
                //模型总数
                $_GET['mocount'] = 1;
            }

            //当全部模型重建时处理
            if ( $modelid == 0 ) {

                $modelCONUT = Db("Model")->count();

                $modelDATA = Db::name("Model")->where('type',0)->order(array('modelid' => 'ASC'))->find();

                $modelid = $modelDATA['modelid'];

                $_GET['mo'] = 1;

                $_GET['mocount'] = $modelCONUT;

                $_GET['modelid'] = $modelid;
            }

            $models_v = $model[$modelid];

            if (!is_array($models_v)) {

                $this->error("该模型不存在！");

                exit;
            }

            $count = \app\content\model\Content::getInstance($modelid)->count();

            // 如果是重建全部模型
            if ($count == 0) {

                if (isset($_GET['mo'])) {
                    $where = array();
                    $where['type'] = 0;
                    $where['modelid'] = array('GT', $modelid);
                    $modelDATA = Db::name('Model')->where($where)->order('modelid','ASC')->find();
                    if (!$modelDATA) {
                        $this->success('Tags重建结束！', url('index'));
                        exit;
                    }
                    unset($_GET['zlun']);
                    unset($_GET['lun']);
                    $modelid = $modelDATA['modelid'];
                    $_GET['modelid'] = $modelid;
                    $this->assign("waitSecond", 200);
                    $this->success("模型：{$models_v['name'] }，第 " . ($lun + 1) . "/{$zlun} 轮更新成功，进入下一轮更新中...", url('create', $_GET));
                    exit;
                } else {
                    $this->error('该模型下没有信息！');
                    exit;
                }
            }
            //总轮数
            $zlun = ceil($count / $mlun);

            $_GET['zlun'] = $zlun;
            
            $this->createUP($models_v, $firstRow, $mlun);
            if ($lun == (int) $_GET['zlun'] - 1) {
                if (isset($_GET['mo'])) {
                    $where = array();
                    $where['type'] = 0;
                    $where['modelid'] = array('GT', $modelid);
                    $modelDATA = Db::name('Model')->where($where)->order(array('modelid' => 'ASC'))->find();
                    if (!$modelDATA) {
                        $this->success("Tags重建结束！", url('index'));
                        exit;
                    }
                    unset($_GET['zlun']);
                    unset($_GET['lun']);
                    $modelid = $modelDATA['modelid'];
                    $_GET['modelid'] = $modelid;
                } else {
                    $this->success("Tags重建结束！", url('index'));
                    exit;
                }
            } else {
                $_GET['lun'] = $lun + 1;
            }
            $this->assign('waitSecond', 200);
            $this->success("模型：" . $models_v['name'] . "，第 " . ($lun + 1) . "/$zlun 轮更新成功，进入下一轮更新中...", url('create', $_GET));
            exit;
        } 

        $model = hk_cache('Model');

        $mo = array();

        foreach ($model as $k => $v) {

            if ($v['type'] == 0) {

                $mo[$k] = $v['name'];
            }
        }

        $this->assign('Model', $mo);

        return $this->fetch();
        
    }

    //数据重建
    protected function createUP($models_v, $firstRow, $mlun) 
    {
        $db = Db::name('TagsContent');

        $tagdb = Db::name('Tags');

        $keywords = Db::name(ucwords($models_v['tablename']))->where("status",99)->order(array("id" => "ASC"))->limit("{$firstRow},{$mlun}")->column("id,id,keywords,tags,url,title,catid,updatetime");
        
        foreach ($keywords as $keyword) {
            $data = array();
            $time = time();
            $key = strpos($keyword['tags'], ',') !== false ? explode(',', $keyword['tags']) : explode(' ', $keyword['tags']);
            foreach ($key as $key_v) {
                if (empty($key_v) || $key_v == "") {
                    continue;
                }
                $key_v = trim($key_v);
                if ($tagdb->where('tag',$key_v)->column('tagid')) {
                    $tagdb->where('tag',$key_v)->setInc('usetimes');
                } else {
                    $tagdb->insert(array(
                        "tag" => $key_v,
                        "usetimes" => 1,
                        "lastusetime" => $time,
                        "lasthittime" => $time,
                    ));
                }
                $data = array(
                    'tag' => $key_v,
                    "url" => $keyword['url'],
                    "title" => $keyword['title'],
                    "modelid" => $models_v['modelid'],
                    "contentid" => $keyword['id'],
                    "catid" => $keyword['catid'],
                    "updatetime" => $time,
                );
                $db->insert($data);
            }
        }
        return true;
    }

}
